package com.open.capacity.notice.provider.wechat;

import java.io.IOException;
import java.util.Map;
import java.util.function.Consumer;

import com.open.capacity.notice.provider.NoticeTemplate;
import com.open.capacity.notice.provider.core.NoticeProvider;
import com.open.capacity.notice.provider.core.http.ThOkHttp3Template;
import com.open.capacity.notice.provider.core.http.interactive.req.ThRequest;
import com.open.capacity.notice.provider.wechat.chain.WechatMessageChain;
import com.open.capacity.notice.provider.wechat.chain.context.WechatMessageContext;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

/**
 * 微信模板方法 
 */
@Data
@RequiredArgsConstructor
public class WechatTemplate implements NoticeTemplate {

	private static final String CODE = NoticeProvider.WECHAT.getCode();

	private final ThOkHttp3Template thOkHttp3Template;

	private final WechatProperties wechatProperties;

	private final WechatMessageChain wechatMessageChain;

	private final SyncWechatOperations channelOps = new SyncWechatOperations(this);
	private final AsyncWechatOperations asyncChannlOps = new AsyncWechatOperations(this);

	@SuppressWarnings("unchecked")
	public WechatProperties getProperties() {
		return wechatProperties;
	}

	@SuppressWarnings("unchecked")
	public SyncWechatOperations opsForChannel() {
		return channelOps;
	}

	@SuppressWarnings("unchecked")
	public AsyncWechatOperations asyncOpsForChannel() {
		return asyncChannlOps;
	}

	@Override
	public boolean supports(String code) {
		return CODE.equals(code);
	}

	@Override
	@SneakyThrows
	public <REQ extends ThRequest> void sendText(REQ request, Consumer<Map<String, Object>> success,
			Consumer<IOException> failure) throws IOException {

		// 微信可能有文本消息和文件消息，需要使用额外处理，使用责任链二次分发
		WechatMessageContext context = WechatMessageContext.builder().wechatTemplate(this).req(request).success(success)
				.failure(failure).build();

		wechatMessageChain.execute(context);

	}

}